package t10086.WorkThread;

import t10086.Data.Broadcast;
import t10086.Model.Messages.Message;
import t10086.Model.Messages.MessageType;
import t10086.WorkThread.Shared.DataBuffer;

import java.io.*;
import java.net.InetSocketAddress;
import java.util.concurrent.BlockingQueue;

class DeepCopy {
    // 深度拷贝方法
    public static <T> T deepCopy(T original) throws IOException, ClassNotFoundException {
        // 将对象写入到字节流中
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(original);

        // 从字节流中读取对象
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

        return (T) objectInputStream.readObject();
    }
}

public class Sender implements Runnable {
    private final BlockingQueue<Message> queue;
    private final ObjectOutputStream out;
    private final InetSocketAddress client;
    public Sender(InetSocketAddress client, BlockingQueue<Message> queue, ObjectOutputStream out) {
        this.queue = queue;
        this.out = out;
        this.client = client;
    }
    @Override
    public void run() {
    while (true) {
        try {

            Message msg = queue.take();
            Message sendMsg = DeepCopy.deepCopy(msg);
            out.writeObject(sendMsg);
            out.flush();;
          //  System.out.println("Sending: " + sendMsg);
        } catch (InterruptedException e) {
            System.out.printf("Sender for [%s] interrupted\n",client);
            break;
        } catch (IOException e) {
            System.out.printf("Sender for [%s] IOException\n",client);
            break;
        } catch (ClassNotFoundException e) {
            System.out.printf("Sender for [%s] ClassNotFoundException\n",client);
        }
    }


    }
}
